<script setup lang="ts">
  import axios from '@/utils/axios';
  import {ref, reactive, onMounted, onUnmounted} from 'vue';

  // 游戏基本信息
  const gameAvatar = ref("https://example.com/black-myth-wukong-avatar.jpg");
  const gameName = ref("黑神话：悟空");
  const functionBtnTexts = ref(["存档解析", "黑神话地图", "通关凭证"]);

  // 帖子数据
  const state = reactive({
    page: 1,
    listLoading: false,    // 列表加载状态
    refreshLoading: false, // 下拉刷新加载状态
    finished: false,       // 加载完成状态
    postsList: []
  });

  /**
   * 初始化帖子数据
   */
  const initPosts = () => {

    // 设置加载状态
    if (state.page === 1 && !state.refreshLoading) {
      state.listLoading = true;
    } else if (state.page > 1) {
      state.listLoading = true;
    }

    // 固定游戏ID为1
    axios.post("/api/hotStop/getGamesId/4/"+state.page)
        .then(res => {
          const newData = res.data || [];
          if (state.page === 1) {
            state.postsList = newData;
          } else {
            state.postsList = [...state.postsList, ...newData];
          }

          // 判断是否加载完成
          state.finished = newData.length === 0;
        })
        .catch(err => {
          console.error("获取游戏帖子失败:", err);
          state.finished = true;
        })
        .finally(() => {
          state.listLoading = false;
          state.refreshLoading = false;
        });
  };

  /**
   * 下拉刷新处理
   */
  const handleRefresh = () => {
    state.page = 1;
    state.finished = false;
    state.refreshLoading = true;
    initPosts();
  };

  /**
   * 加载更多数据
   */
  const loadMore = () => {
    if (state.finished || state.listLoading) return;
    state.page++;
    initPosts();
  };

  /**
   * 滚动事件处理 - 实现上拉加载
   */
  const handleScroll = () => {
    if (state.listLoading || state.finished) return;

    const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
    const clientHeight = document.documentElement.clientHeight || window.innerHeight;
    const scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;

    // 距离底部50px时加载更多
    if (scrollTop + clientHeight >= scrollHeight - 50) {
      loadMore();
    }
  };

  // 页面挂载时初始化数据
  onMounted(() => {
    initPosts();
    window.addEventListener('scroll', handleScroll);
  });

  onUnmounted(() => {
    window.removeEventListener('scroll', handleScroll);
  });

  /**
   * 时间格式化工具函数
   * @param timestamp - 时间戳字符串
   * @returns 格式化后的时间文本
   */
  const formatTime = (timestamp: string): string => {
    const now = new Date();
    const postTime = new Date(timestamp);
    const diffInHours = (now.getTime() - postTime.getTime()) / (1000 * 60 * 60);

    if (diffInHours < 1) {
      return `${Math.floor(diffInHours * 60)}分钟前`;
    }
    if (diffInHours < 24) {
      return `${Math.floor(diffInHours)}小时前`;
    }
    if (diffInHours < 48) {
      return `昨天 ${postTime.getHours().toString().padStart(2, '0')}:${postTime.getMinutes().toString().padStart(2, '0')}`;
    }
    if (postTime.getFullYear() === now.getFullYear()) {
      return `${postTime.getMonth() + 1}-${postTime.getDate()}`;
    }
    return `${postTime.getFullYear()}-${postTime.getMonth() + 1}-${postTime.getDate()}`;
  };
</script>

<template>
  <div class="game-detail-page">
    <!-- 下拉刷新容器 -->
    <van-pull-refresh v-model="state.refreshLoading" @refresh="handleRefresh" class="refresh-container">
      <div class="content-wrapper">
        <!-- 游戏头部信息 -->
        <div class="game-header">
          <div class="game-info">
            <img :src="gameAvatar" alt="游戏头像" class="game-avatar" />
            <div class="game-name-wrap">
            <span class="game-name" v-if="state.postsList && state.postsList.length > 0">
              {{ state.postsList[0].games?.gameName || gameName }}
            </span>
              <span class="game-name" v-else>
              {{ gameName }}
            </span>
            </div>
          </div>

          <div class="function-buttons">
            <button class="func-btn" v-for="btnText in functionBtnTexts" :key="btnText">
              {{ btnText }}
            </button>
          </div>
        </div>

        <!-- 帖子列表 -->
        <div class="content-list">
          <router-link
              v-for="(item, index) in state.postsList"
              :key="index"
              :to="{ name: 'PostDetails', params: { postId: item.postId } }"
              class="content-item"
          >
            <!-- 文本区域 -->
            <div class="text-area">
              <h3>{{ item.title }}</h3>
              <div class="info-container">
                <p class="info">
                  {{ formatTime(item.publishTime) }} ·
                  <span class="category">{{ item.games?.gameName }}</span>
                </p>
                <div class="comment-count">
                  <van-icon name="chat-o" />
                  <span>{{ item.commentCount }}</span>
                </div>
              </div>
            </div>

            <!-- 缩略图 -->
            <img
                :src="item.postImages && item.postImages.length > 0 ? item.postImages[0].imageUrl : ''"
                alt="内容图片"
                class="item-image"
                v-if="item.postImages && item.postImages.length > 0"
            />
            <div class="item-image-placeholder" v-else></div>
          </router-link>
        </div>
      </div>
    </van-pull-refresh>
  </div>
</template>

<style scoped>
  .game-detail-page {
    background-color: #f5f5f5;
    min-height: 100vh;
  }

  .game-header {
    display: flex;
    align-items: center;
    background-color: #554a42;
    padding: 10px;
    border-radius: 8px;
    margin: 10px;
  }

  .game-info {
    display: flex;
    align-items: center;
    margin-right: 15px;
  }

  .game-avatar {
    width: 60px;
    height: 60px;
    border-radius: 50%;
    margin-right: 10px;
    object-fit: cover;
  }

  .game-name-wrap {
    display: flex;
    align-items: center;
  }

  .game-name {
    font-size: 18px;
    color: #fff;
    margin-right: 5px;
  }

  .function-buttons {
    display: flex;
    flex-wrap: nowrap;
    overflow-x: auto;
    padding: 5px 0;
  }

  .func-btn {
    background-color: #7a6c64;
    color: #fff;
    border: none;
    padding: 6px 12px;
    margin-right: 8px;
    border-radius: 4px;
    cursor: pointer;
    font-size: 14px;
    white-space: nowrap;
    transition: background-color 0.2s;
  }

  .func-btn:last-child {
    margin-right: 0;
  }

  .func-btn:hover {
    background-color: #8b7a72;
  }

  .content-list {
    flex: 1;
    overflow-y: auto;
    padding: 10px;
    background-color: #fff;
  }

  .content-item {
    display: flex;
    align-items: center;
    margin-bottom: 12px;
    border-bottom: 1px solid #eee;
    padding-bottom: 12px;
    transition: background-color 0.2s ease;
    cursor: pointer;
    text-decoration: none;
  }

  .content-item:last-child {
    border-bottom: none;
  }

  .content-item:hover {
    background-color: #f9f9f9;
  }

  .text-area {
    flex: 1;
    margin-right: 12px;
  }

  .text-area h3 {
    font-size: 16px;
    margin: 0;
    line-height: 1.5;
    color: #333;
    font-weight: 500;
  }

  .info-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 12px;
    color: #999;
    margin-top: 5px;
  }

  .info {
    margin: 0;
    flex: 1;
  }

  .comment-count {
    display: flex;
    align-items: center;
    gap: 4px;
    color: #666;
    font-size: 12px;
  }

  .category {
    color: #666;
    font-size: 12px;
    background-color: #f0f0f0;
    padding: 2px 6px;
    border-radius: 4px;
    margin-left: 5px;
  }

  .item-image {
    width: 150px;
    height: 75px;
    object-fit: cover;
    border-radius: 8px;
    box-shadow: 0 1px 3px rgba(0,0,0,0.1);
  }

  .item-image-placeholder {
    width: 150px;
    height: 75px;
    background-color: #f0f0f0;
    border-radius: 8px;
    box-shadow: 0 1px 3px rgba(0,0,0,0.1);
  }

  .refresh-container {
    /* 关键：让刷新容器占满屏幕高度 */
    height: 100vh;
    overflow-y: auto;
    -webkit-overflow-scrolling: touch; /* 启用iOS原生滚动优化 */
  }

  .content-wrapper {
    /* 避免内容被底部导航遮挡 */
    padding-bottom: 60px;
  }
</style>
